<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\GoldModel;
use App\Models\OrderHistoryModel;
use App\Models\OrderModel;
use App\Models\UserPayOrderModel;
use App\Utils\Payment\DaiFaPayment;
use App\Utils\ResponseEnum;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Yansongda\Pay\Exception\ContainerException;

class PayController extends ApiController
{
	public function web($order, $payOrder) {
        return '';
    }

    /**
     * APP支付
     * @throws ContainerException
     */
    public function app($order, $payOrder): string
    {
        $payment = new DaiFaPayment();
        $response = $payment->appPay('代发商品支付订单' . $order->order_no, $order->order_no, $payOrder->money);
        return $response->getBody()->getContents();
    }

    /**
     * 订单支付宝支付
     * @param Request $request
     * @return JsonResponse|string
     * @throws ContainerException
     * @throws BusinessException
     */
    public function orderPaymentPay(Request $request): JsonResponse|string
    {
        $orderNo = $this->verifyString('order_no');
        $order = OrderModel::where('order_no', $orderNo)->first();
        if (!$order)
            return $this->fail(ResponseEnum::CLIENT_DELETED_ERROR);
        // 抵扣金币判断
        if ($order->gold && $order->gold > GoldModel::where('uid', $order->uid)->where('status', 1)->sum('gold'))
            return $this->fail(ResponseEnum::CLIENT_NOT_FOUND_HTTP_ERROR);
        // 支付订单记录
        $money =  $order->goods_total + $order->express_fee + $order->daifa_fee + $order->check_fee + $order->package_fee + $order->brand_fee + $order->wishcard_fee - $order->gold;
        $payOrder = UserPayOrderModel::createPayOrder($order->uid, $order->order_no, round($money, 2),3);
        OrderHistoryModel::createHistoryOrder($order);
        if (!$request->input('web'))
            return $this->web($order, $payOrder);
        else {
            $content = $this->app($order, $payOrder);
            return $this->success(['pay_str' => $content, 'order_id' => $order->id]);
        }

    }
}
